package com.cgsrp.cgsrp_community.controller;

import com.cgsrp.cgsrp_community.domain.*;
import com.cgsrp.cgsrp_community.service.*;
import com.cgsrp.utils.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("community")
public class CommunityController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private BlogLikeService blogLikeService;

    @Autowired
    private BlogFollowService blogFollowService;

    @Autowired
    private BlogCommentService blogCommentService;

    @Autowired
    private BlogCommentBadService blogCommentBadService;

    @Resource
    private RedisTemplate redisTemplate;


    @Resource
    private RestHighLevelClient restHighLevelClient;



    @GetMapping("tlist")
    public PageInfo<Blog> tlist(
            @RequestParam(defaultValue = "1")Integer curPage,
            @RequestParam(defaultValue = "24")Integer pageSize,
            @RequestParam(defaultValue="")String searchKey
    ){
        return blogService.tlist(curPage,pageSize,searchKey);
    }

    @GetMapping("glist")
    public PageInfo<Blog> glist(
            @RequestParam()int userId,
            @RequestParam(defaultValue = "1")Integer curPage,
            @RequestParam(defaultValue = "24")Integer pageSize,
            @RequestParam(defaultValue="")String searchKey
    ){
        return blogService.glist(userId,curPage,pageSize,searchKey);
    }

    @GetMapping("getLike")
    public Result getLike(int id){
        return blogLikeService.getLike(id);
    }
    @GetMapping("getFollow")
    public Result getFollow(int id){
        return blogFollowService.getFollow(id);
    }

    @PostMapping("like")
    public Result like(BlogLike blogLike){
        return blogLikeService.like(blogLike);
    }

    @PostMapping("dlike")
    public Result dlike(BlogLike blogLike){
        return blogLikeService.dlike(blogLike);
    }

    @PostMapping("followYou")
    public Result followYou(BlogFollow blogFollow){
        return blogFollowService.addFollow(blogFollow);
    }

    @PostMapping("dfollowYou")
    public Result dfollowYou(BlogFollow blogFollow){
        return blogFollowService.nFollow(blogFollow);
    }

    @PostMapping("sendComment")
    public Result sendComment(BlogComment blogComment){
        String result = TextCensor.TextCensor(blogComment.getContent());
        ObjectMapper objectMapper = new ObjectMapper();
        BaiduResult baiduResult = new BaiduResult();
        try {
            baiduResult = objectMapper.readValue(result, BaiduResult.class);
            if (baiduResult.getConclusionType()!=1){
                BlogCommentBad blogCommentBad = new BlogCommentBad();
                blogCommentBad.setBlogId(blogComment.getBlogId());
                blogCommentBad.setUserId(blogComment.getUserId());
                blogCommentBad.setParentId(blogComment.getParentCommentId());
                blogCommentBad.setContent(result);
                blogCommentBadService.insert(blogCommentBad);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("评论不合法:");
                for (BaiduResultData datum : baiduResult.getData()) {
                    String s=datum.getMsg()+"; ";
                    stringBuilder.append(s);
                }
                return Result.failure(stringBuilder.toString());
            }
            blogComment.setCreateTime(new Date());
            int i = blogCommentService.insert(blogComment);
            GetIndexRequest request = new GetIndexRequest("blog");
            boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
            if (exists){
                DeleteIndexRequest request1 = new DeleteIndexRequest("blog");
                restHighLevelClient.indices().delete(request1, RequestOptions.DEFAULT);
            }
            redisTemplate.delete("blog_follow");
            redisTemplate.delete("blog");
            if (i>0){
                return Result.suc("评论成功",blogComment);
            }else {
                return Result.fai("系统故障",blogComment);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("getFollowUsers")
    public Result getFollowUsers(Integer id){
        return blogFollowService.findFollowUsers(id);
    }

    @GetMapping("getBlogByUserId")
    public Result getBlogByUserId(
            @RequestParam()int userId,
            @RequestParam(defaultValue = "1")Integer curPage,
            @RequestParam(defaultValue = "24")Integer pageSize,
            @RequestParam(defaultValue="")String searchKey
    ){
        return blogService.getBlogByUserId(userId,curPage,pageSize,searchKey);
    }

    @PostMapping("delete")
    public Result delete(Blog blog){
        try {
            blog.setRecommendationLevel(-1);
            int i = blogService.updateByPrimaryKeySelective(blog);
            GetIndexRequest request = new GetIndexRequest("blog");
            boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
            if (exists){
                DeleteIndexRequest request1 = new DeleteIndexRequest("blog");
                restHighLevelClient.indices().delete(request1, RequestOptions.DEFAULT);
            }
            redisTemplate.delete("blog_follow");
            redisTemplate.delete("blog");
            if (i>0){
                return Result.success("删除成功");
            }else {
                return Result.failure("删除失败");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("appendImg")
    public Result appendImg(MultipartFile photo){
        try {
            String result = ImgCensor.ImgCensor(photo);
            ObjectMapper objectMapper = new ObjectMapper();
            BaiduResult baiduResult = new BaiduResult();
            baiduResult = objectMapper.readValue(result, BaiduResult.class);
            if(baiduResult.getConclusionType()!=1){
                return Result.failure("图片不合法");
            }else {
                return blogService.uploadFile(photo);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("uploadBlog")
    public Result uploadBlog(Blog blog){
        try {
            blog.setCreatTime(new Date());
            blog.setRecommendationLevel(0);
            int i = blogService.insert(blog);
            if (i>0){
                GetIndexRequest request = new GetIndexRequest("blog");
                boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
                if (exists){
                    DeleteIndexRequest request1 = new DeleteIndexRequest("blog");
                    restHighLevelClient.indices().delete(request1, RequestOptions.DEFAULT);
                }
                redisTemplate.delete("blog_follow");
                redisTemplate.delete("blog");
                return Result.success("1");
            }else {
                return Result.failure("2");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("testCheck")
    public BaiduResult testCheck(String msg){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(TextCensor.TextCensor(msg),BaiduResult.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
